package com.digital.library.common.aspect;

import com.digital.library.common.annotation.Permission;
import com.digital.library.common.constant.CommonConstant;
import com.digital.library.common.utils.*;
import com.digital.library.common.vo.Result;
import com.digital.library.modules.system.domain.SysUser;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

/**
 *  权限切面类
 */
@Aspect
@Component
public class PermissionAspect {

    @Autowired
    RedisUtil redisUtil;


    @Pointcut("@annotation(com.digital.library.common.annotation.Permission)")
    public void pointCut() {
    }

    @Around("pointCut()")
    public Object arround(ProceedingJoinPoint point) throws  Throwable{

        HttpServletRequest request = SpringContextUtil.getHttpServletRequest();
        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();
        Permission pd = method.getAnnotation(Permission.class);
        String pers = pd.permission();

        //TODO 通过Token获取用户role，并与pers匹配
        String token = TokenUtils.getTokenByRequest(request);
        String name = JwtUtil.getUsername(token);
        Object object = redisUtil.get(CommonConstant.PREFIX_USER_TOKEN + name);

        if(ObjectConvertUtil.isEmpty(object)){
            //缓存失效
            Result result = new Result();
            result.setCode(403);
            result.setMessage("登录超时，请重新登录！");
            return result;
        }else{
            SysUser user = (SysUser) object;
            if(!pers.equals(user.getRole())){
                //权限校验不通过
                Result result = new Result();
                result.setCode(403);
                result.setMessage("权限不足！");
                return result;
            }
        }
        return point.proceed();
    }
}
